package com.aiti.lulian.service.impl;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.components.wx.WxComponent;
import com.aiti.lulian.dto.EnterpriseDto;
import com.aiti.lulian.dto.WeChatUserCardHolderDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.entity.newCard.CardBaseInfo;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CardEnterpriseUserDataMapper;
import com.aiti.lulian.mapper.LuLianEnterpriseUserMapper;
import com.aiti.lulian.mapper.newCard.CardPersonalBaseInfoMapper;
import com.aiti.lulian.service.*;
import com.aiti.lulian.vo.CardEnterpriseUserDataByBaseIdVo;
import com.aiti.lulian.vo.CardEnterpriseUserDataVo;
import com.aiti.lulian.vo.CardHolderVo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;
import java.util.stream.Collectors;


@Slf4j
@Service
public class CardEnterpriseUserDataServiceImpl extends BaseSerivceImpl<CardEnterpriseUserDataMapper, CardEnterpriseUserData> implements CardEnterpriseUserDataService {

    @Autowired
    private CardHolderService cardHolderService;

    @Autowired
    private ILuLianEnterpriseUserService luLianEnterpriseUserService;

    @Autowired
    private CloudShowManagerSubService managerSubService;

    @Autowired
    private CardEnterpriseTemplateService cardEnterpriseTemplateService;

    @Autowired
    private ILuLianEnterpriseExtensionService luLianEnterpriseExtensionService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CloudShowManagerSubService cloudShowManagerSubService;

    @Autowired
    private LuLianEnterpriseUserMapper luLianEnterpriseUserMapper;

    @Autowired
    private ICardVisitorRecordService cardVisitorRecordService;

    @Autowired
    private ICardOperationLogService cardOperationLogService;

    @Autowired
    private ILuLianEnterpriseService luLianEnterpriseService;

    @Autowired
    private WxComponent wxComponent;

    private Lock lock = new ReentrantLock();

    @Autowired
    private RestTemplate restTemplate;

    private final String GET_WX_USER_OPENID = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    @Autowired
    private CardPersonalBaseInfoMapper cardPersonalBaseInfoMapper;

    @Override
    public List<CardEnterpriseUserData> enterpriseUserDataCount(Page page, CardEnterpriseUserDataVo vo) {
//
        List<CardEnterpriseUserData> result = this.baseMapper.userDataCountList(page, vo);
        return result;


    }

    @Override
    public List<CardHolderVo> findUserCardandCardHolder(WeChatUserCardHolderDto weChatUserCardHolderDto) {
//        CardEnterpriseUserDataAndCardHolderVo cardandCardHolder = this.baseMapper.findUserCardandCardHolder(weChatUserCardHolderDto.getUserId());
//        if (cardandCardHolder == null) {
//            return new CardEnterpriseUserDataAndCardHolderVo();
//        }
        //通过用户id获取用户的收藏夹列表
        List<CardHolderVo> vo = cardHolderService.findCardHolderListByBaseId(weChatUserCardHolderDto.getUserId());
        List<String> userIds = vo.stream().map(CardHolderVo::getCardHolderUserId).collect(Collectors.toList());
        Message usersInfoMessage = cloudShowManagerSubService.getUsersInfo(userIds);
        if(usersInfoMessage.getCode() == MessageCodeConstant.MSG_FAIL_CODE){
            throw new RuntimeException("获取用户信息失败");
        }
        Map<String, Map<String, String>> messageMap= (Map<String, Map<String, String>>) usersInfoMessage.getObj();
        for (CardHolderVo cardHolderVo : vo) {
            Map<String, String> map = messageMap.get(cardHolderVo.getCardHolderUserId());
            if (map == null) {
                cardHolderVo.setUserName("");
                cardHolderVo.setPosition("");
                cardHolderVo.setPositionTwo("");
                cardHolderVo.setPositionThree("");
                cardHolderVo.setPositionFour("");
                cardHolderVo.setHeaderUrl("");
                cardHolderVo.setRealname("");
                cardHolderVo.setScreenshotUrl("");
                cardHolderVo.setFixedPhone("");
                cardHolderVo.setCommonName("");
                cardHolderVo.setShareTitle("");
            } else {
                //设置收藏夹用户的名称(也是手机号)
                cardHolderVo.setUserName(map.get("username"));
                //设置收藏夹用户的职位一
                cardHolderVo.setPosition(map.get("position"));
                //设置收藏夹用户的职位二
                cardHolderVo.setPositionTwo(map.get("positionTwo"));
                //设置收藏夹用户的职位三
                cardHolderVo.setPositionThree(map.get("positionThree"));
                //设置收藏夹用户的职位四
                cardHolderVo.setPositionFour(map.get("positionFour"));
                //设置收藏夹用户的头像
                cardHolderVo.setHeaderUrl(map.get("headerUrl"));
                //设置收藏夹用户的真实姓名
                cardHolderVo.setRealname(map.get("realname"));
                //设置截图URL
                cardHolderVo.setScreenshotUrl(map.get("screenshotUrl"));
                //座机号（政府名片）
                cardHolderVo.setFixedPhone(map.get("fixedPhone"));
                //企业名称（手输）
                cardHolderVo.setCommonName(map.get("commonName"));
                //转发标题
                String shareTitle = map.get("shareTitle");
                if (StrUtil.isBlank(shareTitle)) {
                    LuLianEnterpriseExtension enterpriseExtension = luLianEnterpriseExtensionService.getOne(new LambdaQueryWrapper<LuLianEnterpriseExtension>().eq(LuLianEnterpriseExtension::getEnterpriseId, cardHolderVo.getEnterpriseId()));
                    if (enterpriseExtension != null) {
                        shareTitle = enterpriseExtension.getShareTitle();
                    }
                }
                cardHolderVo.setShareTitle(shareTitle);
            }
        }
        return vo;
    }

    @Override
    public Message deleteCardHolder(String baseId) {
        cardHolderService.removeById(baseId);
        return Message.success();
    }

    /***
     *
     * @param userId 发名片的人
     * @param currentUserId 当前登陆人
     * @param from
     * @return
     */
    @Override
    public CardEnterpriseUserDataByBaseIdVo findUserCardInfoByBaseId(String userId, String currentUserId, String from, String loginCode, String source) {

        if(!StringUtils.equals(userId,currentUserId)){
            String enterpriseName = luLianEnterpriseService.selectUserBindEnterpriseName(currentUserId);

            Message message = cloudShowManagerSubService.queryUserOpenIdByUserId(Arrays.asList(userId, currentUserId));
            if(message.getCode().equals(MessageCodeConstant.MSG_SUCCESS_CODE)){
                List<LinkedHashMap> obj = (List<LinkedHashMap>)message.getObj();
                if(obj != null && obj.size() > 0){
                    if(StringUtils.equals(from,"1")){
                        Map<String, LinkedHashMap> userInfo = obj.stream().collect(Collectors.toMap(k -> (String)k.get("baseId"), Function.identity()));
                        //被访问人
                        LinkedHashMap bfwr = userInfo.get(userId);
                        if(bfwr != null){
                            LinkedHashMap fwr = null;
                            if(StringUtils.equals(currentUserId,"isNotLogin") || StringUtils.isBlank(currentUserId)){
                                fwr = new LinkedHashMap<String,String>();
                            }else{
                                fwr = userInfo.get(currentUserId);
                            }
                            String bfwrOpenId = (String)bfwr.get("openId");
                            if(StringUtils.isNotBlank(bfwrOpenId)){
                                String userName = "";
                                String position = "";
                                String phonenumber = "";
                                if(fwr != null){
                                    userName = (String)fwr.get("userName");
                                    position = (String)fwr.get("position");
                                    phonenumber = (String)fwr.get("phonenumber");
                                }
                                wxComponent.sendCardAccessTip(userId, bfwrOpenId,userName,position,enterpriseName,currentUserId,phonenumber);
                            }
                        }
                    }else if(StringUtils.equals(from,"2")){
                        //收藏时候调用的
                    }

                }
            }
        }

        CardEnterpriseUserDataByBaseIdVo cardEnterpriseUserDataByBaseIdVo;  //获取主营产品
        try {
            lock.lock();
            cardEnterpriseUserDataByBaseIdVo = this.baseMapper.findUserCardInfoByBaseId(userId);

            if(cardEnterpriseUserDataByBaseIdVo == null) {
                //若不存在该用户的名片记录，则创建出其名片信息
                CardEnterpriseUserData build = CardEnterpriseUserData.builder().build();
                build.setBaseId(IdUtil.simpleUUID());
                build.setBaseCreateTime(new Date());
                build.setBaseUpdateTime(new Date());
                build.setIsDelete("0");
                build.setSource("3");
                LambdaQueryWrapper<LuLianEnterpriseUser> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(LuLianEnterpriseUser::getUserId, userId);
                List<LuLianEnterpriseUser> list = luLianEnterpriseUserMapper.selectList(wrapper);
                if (list != null && list.size() > 1) {
                    log.error("id为【{}】的用户企业关联数据存在多条，请及时处理！", userId);
                    throw new RuntimeException("对方名片信息有误，无法进行预览");
                } else if (list == null || list.isEmpty()) {
                    build.setEnterpriseId(null);
                } else {
                    build.setEnterpriseId(list.get(0).getEnterpriseId());
                }
                build.setUserId(userId);
                build.setCreator(userId);
                this.save(build);
                cardEnterpriseUserDataByBaseIdVo = this.baseMapper.findUserCardInfoByBaseId(userId);
            }

            CardEnterpriseUserData cardEnterpriseUserData = this.baseMapper.getById(userId);
            if (StrUtil.equals(currentUserId, "isNotLogin") && StrUtil.isNotBlank(loginCode)) {
                String findUrl = String.format(GET_WX_USER_OPENID, "wx7ca766313703d868", "ee06b7594ea4239ab55153d1bae9461c", loginCode);
                ResponseEntity<String> forEntity = restTemplate.getForEntity(findUrl, String.class);
                if(forEntity.getStatusCode().is2xxSuccessful()) {
                    String body = forEntity.getBody();
                    JSONObject jsonObject = JSONObject.parseObject(body);
                    String unionid = jsonObject.getObject("unionid", String.class);
                    currentUserId = "微信用户" + unionid;
                }
            }
            //只有在 StrUtil.equals("1", from) 并且 非“自己查看自己名片”的情况下，才会进入下面访客逻辑
            if((cardEnterpriseUserData != null) && (StrUtil.equals("1", from)) && (! StrUtil.equals(currentUserId, userId))
                    && (! StrUtil.equals(currentUserId, "undefined")) && (! StrUtil.equals(userId, "undefined"))){

                //Redis构建Key:当前登录人 + @ + 发名片人Id
                String viewRedisKey = "view_count:" + currentUserId + "@" + userId;

                if(!redisTemplate.hasKey(viewRedisKey) || (StrUtil.equals(currentUserId, "isNotLogin"))) {
                    System.out.println("不存在viewRedisKey:" + viewRedisKey);
                    //获取当前时间
                    LocalDateTime now = LocalDateTime.now();
                    LocalDateTime localTime = now.withHour(23).withMinute(55).withSecond(59);
                    if (now.isAfter(localTime)) {
                        //如果当前时间过了设置的23点55分则设置第二天的23点55分
                        localTime = localTime.plusDays(1);
                    }
                    long expiryInSeconds = localTime.toEpochSecond(ZoneOffset.UTC) - now.toEpochSecond(ZoneOffset.UTC);
                    redisTemplate.opsForValue().set(viewRedisKey, "1", expiryInSeconds, TimeUnit.SECONDS);

                    //获取当前用户的被查看名片数量
                    Long toDayCount = cardEnterpriseUserData.getToDayCount() == null ? 0 : cardEnterpriseUserData.getToDayCount();
                    Long viewCount = cardEnterpriseUserData.getViewCount() == null ? 0 : cardEnterpriseUserData.getViewCount();
                    cardEnterpriseUserData.setToDayCount(toDayCount + 1);
                    cardEnterpriseUserData.setViewCount(viewCount + 1);
                    //修改当前用户的名片信息的访问数量
                    this.baseMapper.updateById(cardEnterpriseUserData);
                    //新增或更新访客记录
                    cardVisitorRecordService.insertOrUpdateVisitorRecord(userId, currentUserId, StrUtil.isNotBlank(source) ? source : "others");
                    //新增访问日志
                    CardOperationLog cardOperationLog = CardOperationLog.builder()
                            .userId(userId)
                            .enterpriseId(cardEnterpriseUserDataByBaseIdVo.getEnterpriseId())
                            .visitorUserId(currentUserId)
//                            .visitorEnterpriseId(luLianEnterpriseUserMapper)
                            .type("2")
                            .visitorSource(StrUtil.isNotBlank(source) ? source : "others")
                            .build();

                    //查询并设置访客用户的企业ID进行记录
                    if (StrUtil.isNotBlank(currentUserId)) {
                        List<LuLianEnterpriseUser> enterpriseUserList = luLianEnterpriseUserMapper.selectList(new LambdaQueryWrapper<LuLianEnterpriseUser>().eq(LuLianEnterpriseUser::getUserId, currentUserId));
                        if (enterpriseUserList.size() > 1) {
                            log.error("用户【{}】存在多条企业关联记录，请及时处理");
                        } else if (enterpriseUserList.size() == 0) {
                            cardOperationLog.setVisitorEnterpriseId(null);
                        } else {
                            cardOperationLog.setVisitorEnterpriseId(enterpriseUserList.get(0).getEnterpriseId());
                        }
                    } else {
                        cardOperationLog.setVisitorEnterpriseId(null);
                    }
                    cardOperationLogService.save(cardOperationLog);

                }else{
                    System.out.println("存在viewRedisKey:" + viewRedisKey);
                }
            }
        } finally {
            lock.unlock();
        }

        if(StringUtils.isNotBlank(cardEnterpriseUserDataByBaseIdVo.getMainProduct())){
            cardEnterpriseUserDataByBaseIdVo.setMainProducts(getArray(cardEnterpriseUserDataByBaseIdVo.getMainProduct()));
        }
        //远程调用用户表的服务
        Message userIdMap = cloudShowManagerSubService.getUserInfo(userId);
        if(userIdMap.getCode()==1){
            throw new RuntimeException("获取用户信息失败");
        }
        Map<String,String> obj = (Map<String,String>)userIdMap.getObj();
        if (obj != null) {
            //取出收藏夹用户的名称(也是手机号)
            String username = obj.get("username");
            //取出收藏夹用户的职位一
            String position = obj.get("position");
            //取出收藏夹用户的职位二
            String positionTwo = obj.get("positionTwo");
            //取出收藏夹用户的职位三
            String positionThree = obj.get("positionThree");
            //取出收藏夹用户的职位四
            String positionFour = obj.get("positionFour");
            //获取收藏夹用户的真实姓名
            String realname = obj.get("realname");
            //获取地址
            String address = obj.get("address");
            //邮箱
            String email = obj.get("email");
            //背景ID
            String backgroundId = obj.get("backgroundId");
            //邮箱
            String headerUrl = obj.get("headerUrl");
            //微信
            String weiXin = obj.get("weiXin");
            //名片文本颜色
            String textColor = obj.get("textColor");
            //座机号（政府名片）
            String fixedPhone = obj.get("fixedPhone");
            //企业名称（手输）
            String commonName = obj.get("commonName");
            cardEnterpriseUserDataByBaseIdVo.setUserName(username);
            cardEnterpriseUserDataByBaseIdVo.setPosition(position);
            cardEnterpriseUserDataByBaseIdVo.setPositionTwo(positionTwo);
            cardEnterpriseUserDataByBaseIdVo.setPositionThree(positionThree);
            cardEnterpriseUserDataByBaseIdVo.setPositionFour(positionFour);
            cardEnterpriseUserDataByBaseIdVo.setRealName(realname);
            cardEnterpriseUserDataByBaseIdVo.setAddress(address);
            cardEnterpriseUserDataByBaseIdVo.setEmail(email);
            cardEnterpriseUserDataByBaseIdVo.setBackgroundId(backgroundId);
            cardEnterpriseUserDataByBaseIdVo.setHeaderUrl(headerUrl);
            cardEnterpriseUserDataByBaseIdVo.setWeiXin(weiXin);
            cardEnterpriseUserDataByBaseIdVo.setTextColor(textColor);
            cardEnterpriseUserDataByBaseIdVo.setFixedPhone(fixedPhone);
            cardEnterpriseUserDataByBaseIdVo.setCommonName(commonName);
        }
//            //修改
//            CardAccessRecord cardAccessRecord = cardAccessRecordMapper.getById(userId);
//            if (cardAccessRecord != null){
//                Long toDayCount = cardAccessRecord.getToDayCount();
//                cardAccessRecord.setToDayCount(toDayCount+1);
//                cardAccessRecordMapper.updateById(cardAccessRecord);
//            }
            LambdaQueryWrapper<CardHolder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CardHolder::getCardHolderUserId, userId);
            System.out.println("yyyyy=====>:" + currentUserId);
            System.out.println("zzzzzz=====>:" + userId);
            if (StrUtil.isNotBlank(currentUserId)) {
                //已登录状态下预览分支
                wrapper.eq(CardHolder::getBaseUserId, currentUserId);

                if (cardHolderService.getOne(wrapper) != null) {
                    cardEnterpriseUserDataByBaseIdVo.setIsCollect(true);
                } else {
                    cardEnterpriseUserDataByBaseIdVo.setIsCollect(false);
                }
            } else {
                //未登录状态下预览分支
                cardEnterpriseUserDataByBaseIdVo.setIsCollect(false);
            }
        System.out.println("xxxxx=====>:" + cardEnterpriseUserDataByBaseIdVo);
        return cardEnterpriseUserDataByBaseIdVo;
    }

    @Override
    public Message collectUserCard(WeChatUserCardHolderDto weChatUserCardHolderDto) {
        // 获取当前登录人的名片id
        String userCardId = weChatUserCardHolderDto.getUserCardId();
        // 要收藏的名片id
        String userHolderCardId = weChatUserCardHolderDto.getUserHolderCardId();
        CardBaseInfo cardBaseInfo = cardPersonalBaseInfoMapper.selectById(userCardId);
        CardBaseInfo holderCardBaseInfo = cardPersonalBaseInfoMapper.selectById(userHolderCardId);
        if (cardBaseInfo == null || holderCardBaseInfo == null) {
            return Message.fail("收藏失败，名片不存在");
        }
        String baseUserId = cardBaseInfo.getUserId();
        String cardHolderUserId = holderCardBaseInfo.getUserId();
        if (baseUserId.equals(cardHolderUserId)) {
            return Message.fail("无法收藏自己拥有的名片");
        }

        List<CardHolder> list = cardHolderService.list(new LambdaQueryWrapper<CardHolder>().eq(CardHolder::getUserCardId, userCardId).eq(CardHolder::getUserHolderCardId, userHolderCardId)
                .eq(CardHolder::getCardHolderUserId, cardHolderUserId).eq(CardHolder::getBaseUserId, baseUserId));
//        // 如果已经收藏过，则取消收藏
//        if (list.size() > 0) {
//            cardHolderService.remove(new LambdaQueryWrapper<CardHolder>().eq(CardHolder::getUserCardId, userCardId).eq(CardHolder::getUserHolderCardId, userHolderCardId));
//            return Message.success("取消收藏成功");
//        } else {
//            //如果没有收藏过，则添加收藏
//
//        }
        if (list.size() == 0) {
            CardHolder cardHolder = new CardHolder();
            cardHolder.setCardHolderUserId(cardHolderUserId);
            cardHolder.setBaseUserId(baseUserId);
            cardHolder.setUserHolderCardId(userHolderCardId);
            cardHolder.setUserCardId(userCardId);
            cardHolderService.save(cardHolder);
        }
//        // 更新访客数据中的交换状态
//        cardVisitorRecordService.update(new LambdaUpdateWrapper<CardVisitorRecord>().eq(CardVisitorRecord::getCardId, userCardId).eq(CardVisitorRecord::getVisitorCardId, userHolderCardId).set(CardVisitorRecord::getExchangeStatus, "2"));
        return Message.success("收藏成功");
    }

    @Override
    public Message myPublishCount(WeChatUserCardHolderDto weChatUserCardHolderDto) {
         //获取当前登录用户的名片信息
        String baseIdLogon = weChatUserCardHolderDto.getBaseId();
        //根据当前登录人的id查询出来当前用户名片详情
        CardEnterpriseUserData cardEnterpriseUserData = this.baseMapper.findUserCardInfoByPhoneBaseIdLogon(baseIdLogon);
        //如果为null，则说明名片不存在
        if(cardEnterpriseUserData==null){
            return Message.fail("当前用户没有名片信息");
        }else {
            //获取当前用户的发布数量
            Long pubCount = cardEnterpriseUserData.getPubCount();
            cardEnterpriseUserData.setPubCount(pubCount+1);
          //修改当前用户的名片信息的发布数量
            this.baseMapper.updateById(cardEnterpriseUserData);
            return Message.success("发布成功");
        }
    }

    @Override
    public void deleteCardAndAccessAndHolder(String userId, String enterpriseId) {
        this.remove(new LambdaQueryWrapper<CardEnterpriseUserData>().eq(CardEnterpriseUserData::getUserId, userId).eq(CardEnterpriseUserData::getEnterpriseId, enterpriseId));
//        cardAccessRecordService.remove(new LambdaQueryWrapper<CardAccessRecord>().eq(CardAccessRecord::getUserId, userId).eq(CardAccessRecord::getEnterpriseId, enterpriseId));
        cardHolderService.remove(new LambdaQueryWrapper<CardHolder>().eq(CardHolder::getBaseUserId, userId));
    }

    public  String [] getArray(String mainProducts){
        String [] mainProductArry=mainProducts.split(",");
        return  mainProductArry;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message createCardAndAccessRecord(String userId, String enterpriseId, String source, String creator) {
        CardEnterpriseUserData cardEnterpriseUserData = CardEnterpriseUserData.builder().userId(userId).enterpriseId(enterpriseId).creator(creator).source(source).build();
        boolean res1 = this.save(cardEnterpriseUserData);

        //当前数据需要保存到show_enterprise_user表中一份
        if(StringUtils.isNotBlank(enterpriseId)){
            LuLianEnterpriseUser enterpriseUser = LuLianEnterpriseUser.builder()
                    .userId(userId)
                    .enterpriseId(enterpriseId)
                    .build();
            luLianEnterpriseUserMapper.insert(enterpriseUser);
        }
//        CardAccessRecord cardAccessRecord = CardAccessRecord.builder().userId(userId).enterpriseId(enterpriseId).build();
//        boolean res2 = cardAccessRecordService.save(cardAccessRecord);
        if (res1) {
            return Message.success();
        } else {
            return Message.fail();
        }
    }

    @Override
    public Message add(String userId, String enterpriseId, String source) {
        if (StrUtil.isBlank(enterpriseId)) {
            List<LuLianEnterpriseUser> enterpriseUserList = luLianEnterpriseUserMapper.selectList(new LambdaQueryWrapper<LuLianEnterpriseUser>()
                    .eq(LuLianEnterpriseUser::getUserId, userId));
            if (enterpriseUserList.size() > 1) {
                log.error("用户【{}】存在多条企业关联数据，请及时处理", userId);
                return Message.fail("该用户存在多条企业关联数据");
            } else if (enterpriseUserList.size() == 1) {
                enterpriseId = enterpriseUserList.get(0).getEnterpriseId();
            }
        }
        CardEnterpriseUserData cardEnterpriseUserData = CardEnterpriseUserData.builder()
                .userId(userId)
                .enterpriseId(enterpriseId)
                .creator(userId)
                .source(source)
                .build();
        this.save(cardEnterpriseUserData);
        return Message.success();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Message setIsCustom(EnterpriseDto enterpriseDto) {
        String layoutNum = "";
        String pubBackgroundStyle = "";
        String pubBackgroundUrl = "";
        String isShare = enterpriseDto.getIsShare();
        String enterpriseId = enterpriseDto.getEnterpriseId();
        if (StrUtil.equals(enterpriseDto.getIsCustom(), "0")) {
            layoutNum = enterpriseDto.getLayoutNum();
            LuLianEnterpriseExtension enterpriseExtension = luLianEnterpriseExtensionService.getOne(new LambdaQueryWrapper<LuLianEnterpriseExtension>().eq(LuLianEnterpriseExtension::getEnterpriseId, enterpriseId));
            if (! StrUtil.equals(layoutNum, enterpriseExtension.getLayoutNum())) {
                //将指定的布局下的第一个名片背景更新到该企业下的每一位员工信息中
                //(1)获取该布局下的第一个背景ID作为默认背景
                List<CardEnterpriseTemplate> templateList = cardEnterpriseTemplateService.list(new LambdaQueryWrapper<CardEnterpriseTemplate>()
                        .eq(CardEnterpriseTemplate::getEnterpriseId, enterpriseId)
                        .eq(CardEnterpriseTemplate::getLayoutNum, layoutNum)
                        .eq(CardEnterpriseTemplate::getIsDelete, 0));
                Map<String, Object> subUserDtoMap = new HashMap<>();
                if (templateList.size() == 0) {
                    log.error("未查询到企业【ID：{}】下布局编号为【{}】的名片背景，请检查参数【layoutNum】的准确性", enterpriseId, layoutNum);
                } else {
                    //(2)获取该公司下全部人员的用户ID
                    List<String> userIds = luLianEnterpriseUserService.list(new LambdaQueryWrapper<LuLianEnterpriseUser>().eq(LuLianEnterpriseUser::getEnterpriseId, enterpriseId))
                            .stream().map(LuLianEnterpriseUser::getUserId)
                            .collect(Collectors.toList());
                    if (userIds.size() > 0) {
                        //(3)批量更新用户数据
                        subUserDtoMap.put("backgroundId", templateList.get(0).getBaseId());
                        subUserDtoMap.put("userIds", userIds);
                        Message updateSubUserBatchMessage = managerSubService.updateSubUserBatch(subUserDtoMap);
                        if (updateSubUserBatchMessage == null) {
                            throw new RuntimeException("更新用户数据失败");
                        } else if (! MessageCodeConstant.MSG_SUCCESS_CODE.equals(updateSubUserBatchMessage.getCode())) {
                            throw new RuntimeException("更新用户信息失败");
                        }
                    } else {
                        log.error("用户【ID为：{}】与企业【ID：{}】之间缺少关联记录，请及时处理", enterpriseDto.getUserId(), enterpriseId);
                    }
                }
            }
        }
        if (StrUtil.equals(isShare, "0")) {
            pubBackgroundStyle = enterpriseDto.getPubBackgroundStyle();
            pubBackgroundUrl = enterpriseDto.getPubBackgroundUrl();
        }
        LambdaUpdateWrapper<LuLianEnterpriseExtension> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(LuLianEnterpriseExtension::getEnterpriseId, enterpriseDto.getEnterpriseId())
                .set(LuLianEnterpriseExtension::getLayoutNum, layoutNum)
                .set(LuLianEnterpriseExtension::getIsShare, isShare)
                .set(LuLianEnterpriseExtension::getPubBackgroundStyle, pubBackgroundStyle)
                .set(LuLianEnterpriseExtension::getPubBackgroundUrl, pubBackgroundUrl);
        if (StrUtil.isNotBlank(enterpriseDto.getShareTitle())) {
            updateWrapper.set(LuLianEnterpriseExtension::getShareTitle, enterpriseDto.getShareTitle());
        }
        if (StrUtil.isNotBlank(enterpriseDto.getShareTextColor())) {
            updateWrapper.set(LuLianEnterpriseExtension::getShareTextColor, enterpriseDto.getShareTextColor());
        }
        return Message.success(luLianEnterpriseExtensionService.update(updateWrapper));
    }

    @Override
    public boolean hasCard(String phoneNumber) {
        Message queryMessage = cloudShowManagerSubService.isExisting2(phoneNumber);
        if (queryMessage.getCode() != MessageCodeConstant.MSG_SUCCESS_CODE) {
            log.error("查询当前手机号用户是否已创建名片时，在远程调用查询用户信息发生报错，接口入参值为：{}", phoneNumber);
            throw new RuntimeException("远程调用查询用户信息失败");
        }
        String userId = (String) queryMessage.getObj();
        if (StrUtil.equals(userId, "false")) {
            return false;
        }
        List<CardEnterpriseUserData> list = this.list(new LambdaQueryWrapper<CardEnterpriseUserData>().eq(CardEnterpriseUserData::getUserId, userId).eq(CardEnterpriseUserData::getIsDelete, "0"));
        if (list.size() > 1) {
            log.error("查询当前手机号用户是否已创建名片时，查询到名片记录存在多个，接口入参值为：{}", phoneNumber);
            throw new RuntimeException("该手机号用户名片记录存在多条");
        } else if (list.size() == 0) {
            return false;
        } else {
            return true;
        }
    }
}